package com.finger.gulimall.product.service.impl;

import com.finger.gulimall.product.entity.*;
import com.finger.gulimall.product.service.*;
import com.finger.gulimall.product.vo.Attr;
import com.finger.gulimall.product.vo.SkuInfoVo;
import com.finger.gulimall.product.vo.SkuItemAttrGroupVo;
import com.finger.gulimall.product.vo.SkuItemSaleAttrVo;
import jdk.nashorn.internal.ir.BreakableNode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.common.utils.PageUtils;
import com.finger.common.utils.Query;

import com.finger.gulimall.product.dao.SkuInfoDao;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {

        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String min = (String) params.get("min");
        String max = (String) params.get("max");

        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(item -> {
                item.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        if (!StringUtils.isEmpty(min) && !"0".equals(min)) {
            String minPrice = new BigDecimal(min).toString();
            queryWrapper.ge("price", minPrice);
        }
        if (!StringUtils.isEmpty(max) && !"0".equals(max)) {
            String maxPrice = new BigDecimal(max).toString();
            queryWrapper.le("price", maxPrice);
        }
        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id", spuId);

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public SkuInfoVo item(Long skuId) throws ExecutionException, InterruptedException {

        SkuInfoVo skuVo = new SkuInfoVo();

        // 异步编排
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            // 1、商品sku详情 SkuInfoEntity
            SkuInfoEntity info = baseMapper.selectById(skuId);
            skuVo.setInfo(info);
            return info;
        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(info -> {
            // 3、商品spu详情图片 SpuInfoDescEntity
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(info.getSpuId());
            skuVo.setDesc(spuInfoDesc);
        }, executor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(info -> {
            // 4、商品销售属性
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrValueWithSpuId(info.getSpuId());
            skuVo.setSaleAttrVos(saleAttrVos);
        }, executor);

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            // 2、商品sku详情图片 SkuImagesEntity
            List<SkuImagesEntity> skuImages = skuImagesService.getImagesBySkuId(skuId);
            skuVo.setImages(skuImages);
        }, executor);

        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(info -> {
            // 5、1商品基本属性
            List<SkuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithSpuId(info.getCatalogId(), info.getSpuId());
            skuVo.setAttrGroupVos(attrGroupVos);
            // 5.2商品快速属性展示
            List<SkuItemAttrGroupVo> quick = attrGroupVos.stream().filter(item -> {

                List<Attr> quickAttrs = item.getAttrs().stream().filter(item2 -> {
                    return item2.getShowQuick() == 1;
                }).collect(Collectors.toList());
                return quickAttrs.size() > 0;
            }).map(item -> {
                SkuItemAttrGroupVo vos = new SkuItemAttrGroupVo();
                List<Attr> quickAttrs = item.getAttrs().stream().filter(item2 -> {
                    return item2.getShowQuick() == 1;
                }).collect(Collectors.toList());
                BeanUtils.copyProperties(item, vos);
                vos.setAttrs(quickAttrs);
                return vos;
            }).collect(Collectors.toList());
            skuVo.setAttrGroupQuickVos(quick);
        }, executor);

        // 等到所有线程同意执行完，返回
        CompletableFuture.allOf(descFuture, saleAttrFuture, baseAttrFuture, imagesFuture).get();

        return skuVo;
    }


    /**
     * 根据商品id查询商品最新价格
     * @param skus
     * @return
     */
    @Override
    public Map<Long,BigDecimal> getNewItemPriceForCart(List<Long> skus) {
        List<SkuInfoEntity> list = this.baseMapper.selectBatchIds(skus);
        Map<Long, BigDecimal> map = list.stream().collect(Collectors.toMap(SkuInfoEntity::getSkuId, SkuInfoEntity::getPrice));
        return map;
    }
}